<!-- 添加弹窗 -->
<template>
  <el-dialog
    v-if="visible"
    :destroy-on-close="true"
    :lock-scroll="false"
    :visible="visible"
    custom-class="ele-dialog-form"
    title="新建工单"
    width="600px"
    @update:visible="updateVisible">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" @keyup.enter.native="save"
             @submit.native.prevent>
      <el-form-item label="工单类型:" prop="type">
        <el-select v-model="form.type" class="ele-block" clearable placeholder="请选择工单类型">
          <el-option
            v-for="(item, index) in typeList"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务类型:" prop="service_type">
        <el-select v-model="form.service_type" class="ele-block" clearable placeholder="请选择工单类型">
          <el-option
            v-for="(item, index) in serviceTypeList"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务内容:" prop="type">
        <el-select v-model="form.service_content" class="ele-block" clearable placeholder="请选择服务内容">
          <el-option
            v-for="(item, index) in serviceContentList"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划时间" prop="plan_at">
        <el-date-picker
          v-model="form.plan_at"
          format="yyyy-MM-dd"
          placeholder="选择日期"
          type="date"
          value-format="yyyy-MM-dd">
        </el-date-picker
        >
      </el-form-item>


      <el-form-item label="故障现象:" prop="description">
        <el-input v-model="form.description"  placeholder="请输入故障现象" type="textarea" />
      </el-form-item>

      <el-form-item label="优先级:" prop="level">
        <el-radio-group v-model="form.level" class="c-label">
          <el-radio-button
            v-for="(item, index) in tag_nameList"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-radio-group>
      </el-form-item>

      <el-form-item label="客户:" prop="owner_name">
        <el-autocomplete v-model="form.owner_name" :fetch-suggestions="querySearchAsync" class="w-full"
                         placeholder="搜索负责人" value-key="name" @select="handleSelect"></el-autocomplete>
      </el-form-item>

      <el-form-item label="联系人:" prop="contact_name">
        <div style="display: flex;justify-content: space-between" class="contact_nameWrap">
          <el-select v-model="form.contact_name" class="ele-block" clearable placeholder="请选择联系人">
            <el-option
              v-for="(item, index) in contact_nameList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-button  style="margin-left: 10px" type="primary" @click="addCustomerUser" :disabled="!form.customer_id">新建</el-button>
        </div>
      </el-form-item>

      <el-form-item label="联系电话:" prop="contact_phone">
        <el-input
          v-model="form.contact_phone"
          clearable
          placeholder=""/>
      </el-form-item>
      <el-form-item label="所属区域:" prop="areas">
        <el-cascader
          v-model="city"
          :options="regions.cityData"
          class="ele-fluid"
          clearable
          placeholder="请选择省市区"
          popper-class="ele-pop-wrap-higher"/>
      </el-form-item>
      <el-form-item label="详细地址:" prop="address">
        <el-input
          v-model="form.address"
          clearable
          placeholder=""/>
      </el-form-item>

      <el-form-item label="产品:" prop="product_ids" class="product">
        <el-select
          v-model="form.product_ids"
          remote
          multiple
          filterable
          blur
          :remote-method="querySearchProduct"
          clearable
          value-key="id"
          placeholder="请输入关键词"
          :loading="productLoading">
          <el-option
            blur
            v-for="item in productList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            <template #default>
              {{ item.name }}
              型号: <span style="margin-right: 14px;">{{ item.model ? item.model : '无' }}</span>
              编号: <span style="margin-right: 14px;">{{ item.product_number ? item.product_number : '无' }}</span>
          </template>
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item v-if="form.type !== '设备维修'&&form.type !== '安装工单'" label="照片" prop="attachment">
        <el-upload ref="upload" :file-list="attachmentUrl" :http-request="uploadFile" :limit="4"
                   :on-change="uploadHandleChange" :on-remove="handleRemove" accept=".png,.jpg" action=""
                   class="upload-demo -mb-2" list-type="picture">
          <el-button :loading="loading" plain size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">请上传jpg、png图片附件，最多可上传4张，单张大小不要超过8M。</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button
        :loading="loading"
        type="primary"
        @click="save">只保存
      </el-button>
      <el-button
        :loading="loading"
        type="primary"
        @click="save">保存并派单
      </el-button>
    </div>


  </el-dialog>
</template>

<script>
import regions from 'ele-admin/packages/regions';

export default {
  name: 'WorkTicksAdd',
  components:{},
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    // 全部城市数据
    deptList: Array
  },
  data() {
    const validateAreas = (rule, value, callback) => {
      // 判断 country_id province_id city_id county_id 是否为空
      if (!this.city) {
        callback(new Error("请选择地区"));
      } else {
        callback();
      }
    };
    return {
      //客户标签数组
      tag_nameList: [
        "重要",
        "普通",
        "一般",
        "较低",
      ],
      //产品远程搜索加载
      productLoading:false,
      //多选产品
      productList: [],
      // 上传照片
      attachmentUrl: [],
      regions: regions,
      // 选中的省市区
      city: [],
      // 选中的省市
      provinceCity: [],
      // 选中的省
      province: [],
      //客户类型数组
      typeList: [
        "安装工单",
        "设备维修",
        "维保工单",
        "巡检工单",
      ],
      deptLists: [],
      rules: {
        type: [
          {required: true, message: "请选择工单类型", trigger: "blur"}
        ],
        service_content: [
          {required: true, message: "请选择服务内容", trigger: "blur"}
        ],
        plan_at: [
          {required: true, message: "请选择计划时间", trigger: "change"}
        ],
        description: [
          {required: true, message: "请输入故障现象", trigger: "change"}
        ],
        owner_name: [
          {required: true, message: "请选择客户", trigger: "change"}
        ],
        contact_name: [
          {required: true, message: "请选择联系人", trigger: "change"}
        ],
        contact_phone: [
          {required: true, message: "请输入联系电话", trigger: "change"}
        ],
        level: [
          {required: true, message: "请选择优先级", trigger: "change"}
        ],
        areas: [
          {required: true, trigger: "blur", validator: validateAreas}
        ],
        product_ids: [
          {required: true, message: "请选择产品", trigger: "blur"}
        ],
        address: [
          {required: true, message: "请输入详细地址", trigger: "blur"}
        ],
        department_id: [
          {required: true, message: "请选择服务网点", trigger: "change"}
        ],
        attachment: [
          {required: true, message: "请上传图片", trigger: "change"}
        ],
        service_type: [
          {required: true, message: "请选择服务类型", trigger: "change"}
        ],
      },
      //联系人
      contact_nameList:[],
      //客户id
      customer_id:null,
      //服务内容
      serviceContentList:[],
      //服务类型
      serviceTypeList:[],
      //表单数组配置项
      dataList: [],
      // 表单数据
      form: Object.assign({status: 1}, this.data),
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false
    };
  },
  watch: {
    data() {
      this.isUpdate = !!(this.data && this.data.id);
    }
  },
  mounted() {
    this.$http.get(`wos/params`,).then((res) => {
      let temp =res.data.data
     this.serviceTypeList= temp.types
      this.serviceContentList=temp.contents
    });

    this.getdeptList()
  },
  methods: {
    //新增联系人
    addCustomerUser(){
      // this.$emit('addCustomerUser',{id:this.form?.customer_id,name:this.form?.customer_name})
      // this.updateVisible(false)
      // this.$router.push({path:'/c',params: {id:this.form?.customer_id,name:his.form?.customer_name}})
    },
    //添加联系人之后
    reset(){

    },
    //远程搜索产品
    querySearchProduct(query) {
      this.productLoading = true;
      this.$http.get(`products?limit=10&name=${query}`,).then((res) => {
        this.productLoading = false;
        this.productList=res.data.data
      });
    },
    handleSelectProduct(item) {
      this.form.product_id = item.id;
    },
    uploadHandleChange(file) {
      if (file.status === "error") {
        this.$message.error("上传失败");
      }
    },
    uploadFile(file) {
      this.uploadLoading = true;
      const formData = new FormData();
      formData.append("attachment", file.file);

      this.$http.post("files", formData).then((res) => {
        this.form.images.push(res.path);
        this.attachmentUrl.push({name: res.name, url: res.url});
        this.uploadLoading = false;
      });
    },
    handleRemove(file) {
      const index = this.attachmentUrl.findIndex(item => item.url === file.url);
      this.form.images.splice(index, 1);
      this.attachmentUrl.splice(index, 1);
    },
    querySearchAsync(query, cb) {
      query = query ? query : ''
      this.$http.get(`/customers?page=1&limit=10`,{params:{keyword:query}}).then((res) => {
        cb(res.data.data)
      });
    },
    handleSelect(item) {
      this.form.customer_name = item.name
      this.form.customer_id= item.id;
      this.$forceUpdate()
    },
    /* 刷新表格 */
    reload() {
      this.$refs.table?.reload({where: this.where});
    },
    //获取deptList
    getdeptList() {
      const loading = this.$loading({lock: true});
      this.$http.get('/dept/index').then(res => {
        loading.close();
        if (res.data.code === 0) {
          this.deptLists = res.data.data.filter(item => {
            if (item.type == 3) {
              return item
            }
          })
          this.reload();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    },
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form = Object.assign({}, this.form, {
            province_id: this.city[0],
            city_id: this.city[1],
            county_id: this.city[2]
          });
          this.loading = true;
          // if (this.isUpdate) {
          //   this.$http.put(`/wos/${this.data.id}`,
          //     Object.assign({}, this.form, {
          //       pid: this.form.pid || 0
          //     })
          //   ).then(res => {
          //     this.loading = false;
          //     if (res.data.code === 0) {
          //       this.$message.success(res.data.msg);
          //       this.updateVisible(false);
          //       this.form = {}
          //       this.$emit('done');
          //     } else {
          //       this.$message.error(res.data.msg);
          //     }
          //   }).catch(e => {
          //     this.loading = false;
          //     this.$message.error(e.message);
          //   });
          // } else {
            this.$http.post(`/wos`,
              Object.assign({}, this.form, {
                service_type:'保内免费',
                images:this.attachmentUrl
              })
            ).then(res => {
              this.loading = false;
              if (res.data.code === 0) {
                this.$message.success(res.data.msg);
                this.updateVisible(false);
                this.$emit('done');
              } else {
                this.$message.error(res.data.msg);
              }
            }).catch(e => {
              this.loading = false;
              this.$message.error(e.message);
            });
          // }

        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.city=''
      this.form = {}
      this.$emit('reload');
      this.$emit('update:visible', value);
    },
    /* 初始化form数据 */
    initFormData(data) {
      // 初始化默认值
      let form = {level: 1};
      if (data) {
        this.city = [data.province_id, data.city_id, data.county_id]
        this.form = data
        Object.assign(form, data, {
          pid: data.pid === 0 ? null : data.pid,
        });
      }
      return form;
    },
  }
}
</script>

<style scoped>
.el-autocomplete {
  width: 100%;
}
.product/deep/ input{
  width: 460px;
}
.el-input {
  width: 100% !important;
}
.contact_nameWrap/deep/ .el-input{
  width: 200px;
}
</style>
